package com.ruoyi.system.service.impl;

import java.util.*;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.communal.domain.MessageReminder;
import com.ruoyi.communal.mapper.MessageReminderMapper;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.mapper.*;
import com.ruoyi.util.paypassword.PayPassword;
import com.ruoyi.util.TimestampIdGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.service.IWalletService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 钱包Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-01-04
 */
@Service
public class WalletServiceImpl implements IWalletService 
{
    @Resource
    private WalletMapper walletMapper;
    @Resource
    private InAndOutOrderMapper orderMapper;
    @Resource
    private CorpTransactionRecordMapper corpTransactionRecordMapper;
    @Resource
    private WalletBackMapper walletBackMapper;
    @Resource
    private BankMapper bankMapper;
    @Resource
    private SysUserMapper userMapper;
    @Resource
    private MessageReminderMapper messageReminderMapper;
    static MessageReminder messageReminder;
    static List<Long> userIds ;
    static InAndOutOrder order;
    /**
     * 查询钱包
     *
     * @param id 钱包主键
     * @return 钱包
     */
    @Override
    public Wallet selectWalletById(Long id){
        // 添加限制条件或处理多个结果

        return walletMapper.selectWalletById(id);
    }

    /**
     * 查询钱包列表
     * 
     * @param wallet 钱包
     * @return 钱包
     */
    @Override
    public List<Wallet> selectWalletList(Wallet wallet)
    {

        return  walletMapper.selectWalletList(wallet);
    }

    /**
     * 新增钱包
     * 
     * @param  userId 用户id
     * @return 结果
     */
    @Override
    public int insertWallet(Long userId)
    {
        Wallet walletById = selectWalletById(userId);
        if (walletById != null) {
            throw new RuntimeException("钱包已存在");
        }
        Wallet wallet = new Wallet();
        wallet.setId(IdUtils.simpleUUID());
        wallet.setUserId(userId);
        wallet.setBalance(0.0);
        wallet.setDel("0");
        return walletMapper.insertWallet(wallet);
    }


    /**
     * 货物转账功能
     * 
     * @param transfer 转账请求内容
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @PayPassword
    @Override
    public List<Long> transferWallet(TransferRequest transfer) throws InterruptedException {
        userIds = new LinkedList<>();
        userIds.add(transfer.getSenderId());
        userIds.add(transfer.getRecipientId());
        userIds.add(1L);
        List<Wallet> wallets = walletMapper.selectWalletsByUserIds(userIds);

        Wallet sender = null;
        Wallet recipient = null;
        Wallet company = null;
        for (Wallet wallet : wallets) {
            if (Objects.equals(wallet.getUserId(), transfer.getSenderId())){
                sender = wallet;
            }
            if (Objects.equals(wallet.getUserId(), transfer.getRecipientId())){
                recipient = wallet;
            }
            if (Objects.equals(wallet.getUserId(), 1L)){
                company = wallet;
            }
        }
        Double money = transfer.getMoney();

        if (sender.getBalance() < money) {
            throw new RuntimeException("余额不足");
        }
        if (recipient == null) {
            throw new RuntimeException("接收者钱包不存在");
        }
        sender.setBalance(sender.getBalance() - money);
        recipient.setBalance((recipient.getBalance() + (money - money * 0.1)));
        company.setBalance(company.getBalance() + (money * 0.1));
        walletMapper.updateWallet(sender);
        walletMapper.updateWallet(recipient);
        walletMapper.updateWallet(company);

        String Money = String.valueOf(transfer.getMoney()*0.1);
        double Money2 = money - money * 0.1;
        CorpTransactionRecord record = new CorpTransactionRecord(TimestampIdGenerator.nextPkId(), Money, transfer.getSenderId(), 0L, " ", TimestampIdGenerator.getCurrentDateTime(), 1, "0");
        corpTransactionRecordMapper.insertCorpTransactionRecord(record);
        order = new InAndOutOrder( TimestampIdGenerator.nextPkId(),TimestampIdGenerator.getCurrentDateTime(),transfer.getSenderId(),transfer.getRecipientId(),1L,transfer.getMoney(),"0");
        orderMapper.insertInAndOutOrder(order);
        InAndOutOrder order2 = new InAndOutOrder(TimestampIdGenerator.nextPkId(),TimestampIdGenerator.getCurrentDateTime(),transfer.getRecipientId(),transfer.getSenderId(),0L,Money2,"0");
        orderMapper.insertInAndOutOrder(order2);

        List<Long> longList = new ArrayList<>();
        longList.add(order.getId());
        longList.add(order2.getId());
        longList.add(record.getId());
        return longList;
    }

    /**
     * 钱包转入转出功能 转账带银行卡/手机号
     *
     * @param transfer 转账请求内容
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @PayPassword
    @Override
    public int WalletTransaction(TransferRequest transfer) throws InterruptedException {
//       手机号验证
        if (transfer.getPhone() != null){
            SysUser sysUser = new SysUser();
            sysUser.setPhonenumber(transfer.getPhone());
            List<SysUser> sysUsers = userMapper.selectUserList(sysUser);
            if (sysUsers.size() == 0){
                throw new RuntimeException("手机号不存在");
            }
            for (SysUser user : sysUsers) {
                if (user.getPhonenumber().equals(transfer.getPhone())) {
                    transfer.setRecipientId(user.getUserId());
                }
            }
        }
        userIds = new ArrayList<>();
        userIds.add(transfer.getSenderId());
        userIds.add(transfer.getRecipientId());
        List<Wallet> wallets = walletMapper.selectWalletsByUserIds(userIds);
        Wallet sender = null;
        Wallet BankCard = null;
        for (Wallet wallet : wallets) {
            if (Objects.equals(wallet.getUserId(), transfer.getSenderId())){
                sender = wallet;
            }
            if (Objects.equals(wallet.getUserId(), transfer.getRecipientId())){
                BankCard = wallet;
            }
        }
        Double money = transfer.getMoney();
//        转入转出走此处
//        里程表体现走此处 0转入
           if(transfer.getAct() == 0) {
//            转入
               if (BankCard.getBalance() < money) {
                   throw new RuntimeException("来源余额不足");
               }
                   BankCard.setBalance(BankCard.getBalance() - money);
                   sender.setBalance(sender.getBalance() + money);
               } else if (transfer.getAct() == 1) {
//            转出
                   if (sender.getBalance() < money) {
                       throw new RuntimeException("钱包余额不足");
                   }
                   sender.setBalance(sender.getBalance() - money);
                   BankCard.setBalance(BankCard.getBalance() + money);
               }
       walletMapper.updateWallet(BankCard);
         walletMapper.updateWallet(sender);
         order = new InAndOutOrder( TimestampIdGenerator.nextPkId(),TimestampIdGenerator.getCurrentDateTime(),transfer.getSenderId(),transfer.getRecipientId(),transfer.getAct(), money, "0");
        return 1;
    }


    /**
     * 钱包商城  里程表兑换支付功能
     *
     * @param transfer 转账请求内容
     *
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @PayPassword
    @Override
    public int goodsPay(TransferRequest transfer) throws InterruptedException {
        System.out.println("这个是接收者"+transfer.getBackCard());
        Wallet sender = walletMapper.selectWalletById(transfer.getSenderId());
        WalletBack company = walletBackMapper.selectWalletBackById(transfer.getBackCard());
        Double money = transfer.getMoney();
        System.out.println("手上少时诵诗书"+company);
        System.out.println("这个是发送者"+sender);
        if (sender.getBalance() == null || company.getBackBalance() == null){
            throw new RuntimeException("钱包或者银行卡余额不存在");
        }
            if (sender.getBalance() < money) {
                throw new RuntimeException("钱包余额不足");
            }

        double i = Double.parseDouble(company.getBackBalance());
        if (transfer.getAct() == 1){
//                  // 转出  即支付商品金额
                  sender.setBalance(sender.getBalance() - money);
                  company.setBackBalance(String.valueOf(i + money));
              }
             if (transfer.getAct() == 0){
                 // 转入  即收到商品退款金额
//                 // 或者里程表提现也是 转入操作
                 sender.setBalance(sender.getBalance() + money);
                 company.setBackBalance(String.valueOf(i - money));

             }
        walletMapper.updateWallet(sender);
        walletBackMapper.updateWalletBack(company);
        long l = TimestampIdGenerator.nextPkId();
        order = new InAndOutOrder( l, TimestampIdGenerator.getCurrentDateTime(), transfer.getSenderId(), transfer.getCompanyId(),transfer.getAct(), money, "0");
        orderMapper.insertInAndOutOrder(order);

        messageReminder = new MessageReminder();
        messageReminder.setUserMessageId(transfer.getSenderId());
        String s = null;
        if (transfer.getAct() == 0){
            // 转入
//
            s = "您的订单："+l+"，从"+"钱包转出"+money+"元，转入"+"银行卡"+transfer.getBackCard()+"，已完成支付！";
        }else if(transfer.getAct() == 1){
//                  // 转出
            s = "您的订单："+l+"，从"+"钱包转出"+money+"元，转出"+"银行卡"+transfer.getBackCard()+"，已完成支付！";
        }
        messageReminder.setMessage(s);
        messageReminder.setCreateTime(new Date());
        messageReminderMapper.insertMessageReminder(messageReminder);
        return 1;
    }




    @PayPassword
    @Override
    public int updateWallet(Wallet wallet) {
        return walletMapper.updateWallet(wallet);
    }

    /**
     * 批量删除钱包
     * @param ids 需要删除的钱包主键
     * @return 结果
     */
    @Override
    public int deleteWalletByIds(Long[] ids)
    {
        return walletMapper.deleteWalletByIds(ids);
    }

    /**
     * 删除钱包信息
     * 
     * @param id 钱包主键
     * @return 结果
     */
    @Override
    public int deleteWalletById(Long id)
    {
        return walletMapper.deleteWalletById(id);
    }
}
